package com.example.blog_spring.controller;

import com.example.blog_spring.constant.Constants;
import com.example.blog_spring.model.BlogInfo;
import com.example.blog_spring.service.BlogService;
import com.example.blog_spring.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @RequestMapping("/getBlogList")
    public List<BlogInfo> getBlogList(){
        log.info("获取博客列表");
        return blogService.getBlogList();
    }

    @RequestMapping("/getBlogDetailById")
    public BlogInfo getBlogDetailById(Integer blogId, HttpServletRequest request){
        log.info("根据blogId = " + blogId + " 获取博客详情");
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer id = JwtUtils.getIdByToken(token);
        BlogInfo blogInfo = blogService.getBlogDetailById(blogId);
        if(id != null && blogInfo.getUserId() == id){
            blogInfo.setAuthor(true);
        }
        return blogInfo;
    }

    @RequestMapping("/addBlog")
    public Boolean addBook(HttpServletRequest request, @RequestBody BlogInfo blogInfo){ // 使用json
        log.info("添加博客，blogInfo {} ", blogInfo.getTitle());
        if(!StringUtils.hasLength(blogInfo.getTitle())
                || !StringUtils.hasLength(blogInfo.getContent())) {
            return false;
        }
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer id = JwtUtils.getIdByToken(token);
        blogInfo.setUserId(id);
        Integer res = blogService.addBlog(blogInfo);
        return res == 1;
    }

    @RequestMapping("/updateBlog")
    public Boolean updateBlog(BlogInfo blogInfo){
        log.info("更新博客... logInfo: {}", blogInfo.getId());
        if(blogInfo.getId() <= 0 || !StringUtils.hasLength(blogInfo.getTitle())
                || !StringUtils.hasLength(blogInfo.getContent())){
            return false;
        }
        Integer result = blogService.updateBlog(blogInfo);
        return result == 1;
    }

    @RequestMapping("/deleteBlog")
    public boolean deleteBlog(Integer blogId){
        log.info("删除博客... blogId: {}" , blogId);
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(1);
        Integer result = blogService.deleteBlog(blogInfo);
        return result == 1;
    }
}
